package com;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.profile.internal.AwsProfileNameLoader;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.entity.PackCmd;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.Callable;

public class AwsUtils {

    private PackCmd packCmd;
    /**
     * 已经登录的s3
     */
    private AmazonS3 s3Client;
    public static AwsUtils awsUtils;
    /**
     * 当前使用的配置
     */
    private AWSCredentialsProvider credentialsProvider;

    public AwsUtils(Callable<Integer> callable) {
        awsUtils = this;
        this.packCmd = new PackCmd(callable);
    }

    /**
     * 检查账户是否有问题
     */
    public boolean checkAccount() {
        if (StringUtils.isEmpty(this.packCmd.accessKeyId) || StringUtils.isEmpty(this.packCmd.accessKeySecret)) {
            // 如果有一个值是 null
            if (StringUtils.isNotEmpty(this.packCmd.profile)) { // 有传入别名
                System.setProperty(AwsProfileNameLoader.AWS_PROFILE_SYSTEM_PROPERTY, this.packCmd.profile); // 写入系统变量里面  方便 aws sdk 自动获取
            } else {
                this.packCmd.profile = AwsProfileNameLoader.DEFAULT_PROFILE_NAME; // 设置默认值
            }
            System.out.println("*********  使用缓存账户 " + this.packCmd.profile + " 登录  *********");
            this.s3Client = this.build(null).build();
            AWSCredentials awsCredentials = this.credentialsProvider.getCredentials();
            this.packCmd.accessKeyId = awsCredentials.getAWSAccessKeyId();
            this.packCmd.accessKeySecret = awsCredentials.getAWSSecretKey();
            if (StringUtils.isEmpty(this.packCmd.accessKeyId) || StringUtils.isEmpty(this.packCmd.accessKeySecret)) {
                System.out.println("error : profile=[" + this.packCmd.profile + "]");
                return true;
            }
        } else {
            // 手动输入账号密码
            this.s3Client = this.build(this.getAwsStaticCredentialsProvider()).build();
        }
        return false;
    }

    public AmazonS3ClientBuilder build(AWSCredentialsProvider provider) {
        System.out.println("开始连接AWS S3服务器。。。");
        AmazonS3ClientBuilder amazonS3ClientBuilder = AmazonS3ClientBuilder.standard()
                .withRegion(Regions.EU_CENTRAL_1);
        // 添加代理
        File file = new File(Main.getRunPath(),"proxy.conf");
        if (file.exists()) { // 存在代理配置
            try {
                List<String> strings = FileUtils.readLines(file, Charset.defaultCharset());
                String host = null;
                String port = null;
                for (String str: strings) {
                    String[] map = StringUtils.split(str,"=");
                    if (map.length == 2) {
                        if (map[0].equals("proxyHost")) {
                            host = map[1];
                        } else if (map[0].equals("proxyPort")) {
                            port = map[1];
                        }
                    }
                }
                if (!StringUtils.isAnyEmpty(host, port)) {
                    amazonS3ClientBuilder.withClientConfiguration(getCreateClientConfiguration(host, NumberUtils.toInt(port)));
                } else {
                    System.out.println("代理配置数据有错误：" + strings);
                    LoggerFactory.getLogger(getClass()).info("代理配置数据有错误：" + strings);
                }
            } catch (IOException e) {
            }
        } else {
            LoggerFactory.getLogger(getClass()).info("未找到代理配置：" + file.getAbsolutePath());
            System.out.println("未找到代理配置：" + file.getAbsolutePath());
        }
        if (provider != null) {
            amazonS3ClientBuilder.withCredentials(getAwsStaticCredentialsProvider());
        }
        credentialsProvider = amazonS3ClientBuilder.getCredentials();
        return amazonS3ClientBuilder;
    }

    /**
     * 创建代理
     */
    private ClientConfiguration getCreateClientConfiguration(String host, int port) {
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.withProxyHost(host);
        clientConfig.withProxyPort(port);
//        clientConfig.withProtocol(Protocol.HTTPS);
        return clientConfig;
    }


    private AWSStaticCredentialsProvider getAwsStaticCredentialsProvider() {
        BasicAWSCredentials awsCreds = new BasicAWSCredentials(this.packCmd.accessKeyId, this.packCmd.accessKeySecret);
        return new AWSStaticCredentialsProvider(awsCreds);
    }

    public PackCmd getPackCmd() {
        return packCmd;
    }

    public AmazonS3 getS3Client() {
        return s3Client;
    }

    public AWSCredentialsProvider getCredentialsProvider() {
        return credentialsProvider;
    }

}
